﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace LiveService
{
    public class CopyFile
    {
        public File File{get; set;}
        public Folder Source{get; set;}
        public Folder Destination { get; set; }
        public LiveServiceOrmDataContext DataBase { get; set; }
        public string ErreurMessage { get; set; }
        public bool Overwrite { get; set; }

        public CopyFile(File file, Folder source, Folder destination, LiveServiceOrmDataContext db, bool overwrite)
        {
            File = file;
            Source = source;
            Destination = destination;
            DataBase = db;
            Overwrite = overwrite;
        }

        public string run()
        {
            string result = "false";
            if ((result = CopyInBase()) == "true")
                result = CopyPhysique();
            return result;
        }

        private string CopyInBase()
        {
            try
            {
                File newFile = new File();
                newFile.createdon = DateTime.Now;
                newFile.extension = File.extension;
                newFile.id = System.Guid.NewGuid();
                newFile.name = File.name;
                newFile.size = File.size;
                newFile.folderid = Destination.id;

                DataBase.File.InsertOnSubmit(newFile);
                DataBase.SubmitChanges();
                return "true";
            }
            catch (Exception e)
            {
                LService.errmsg += e.Message;
                return "false";
            }
        }

        private string CopyPhysique()
        {
            try
            {
                string sourcePath = System.IO.Path.Combine(Source.internalpath, File.name);
                string destPath = System.IO.Path.Combine(Destination.internalpath, File.name);
                System.IO.File.Copy(sourcePath, destPath, Overwrite);
            }
            catch (System.IO.IOException e)
            {
                LService.errmsg = e.Message;
                return "Exist";
            }
            catch (Exception e)
            {
                LService.errmsg = e.Message;
                return "false";
            }

            return "true";
        }
    }
}